<?php

namespace teach\service;

use Yii;

/** 6折购买规则
 * 直接结算的脚本
 * Class Welfare
 * @package teach\service
 */
class Welfare
{
    public function payAll($oid, $mid, $uid)
    {


        //获取提成参数
        $distribution = $this->distribution($mid);

        //获取此条订单
        $order = $this->sureOrder($oid, $mid, $uid);

        //如果账单小于1元
        if ($order['total_fee'] < 1) {
            // 后台将订单改为已处理
            $this->dealPay($order['p_id']);
            return true;
        }

        //商家自己购买自己的产品
        if ($mid == $uid) {
            //  后台将订单改为已处理
            $this->dealPay($order['p_id']);
            return true;
        }

        //获取下单用户
        $user = $this->userOne($uid);

        //用户绑定了商家 没有上级
        if ($user['mall_superior'] == 0) {
            // 后台将订单改为已处理
            $this->dealPay($order['p_id']);
            return true;
        }

        //用户只有一个上级
        if ($user['mall_top'] == 0) {
            //将佣金打给上级
            $this->superior($uid, $user['mall_superior'], $mid, $order['out_trade_no'], $order['logistic_fee'], $order['total_fee'], $order['p_id'], $distribution['level_one']);
            return true;
        } else {
            //佣金打给上级跟上上级
            $this->top($uid, $user['mall_superior'], $user['mall_top'], $mid, $order['out_trade_no'], $order['logistic_fee'], $order['total_fee'], $order['p_id'], $distribution['level_one'], $distribution['level_two']);
            return true;
        }


    }

    /**
     * 三个层级时，给上级上上级发佣金
     * @param $uid
     * @param $sid
     * @param $tid
     * @param $mid
     * @param $out_trade_no
     * @param $logistic_fee
     * @param $total_fee
     * @param $p_id
     * @param $percent_one
     * @param $percent_two
     */
    private function top($uid, $sid, $tid, $mid, $out_trade_no, $logistic_fee, $total_fee, $p_id, $percent_one, $percent_two)
    {
        //上级用户佣金
        $total_fee_superior = ($total_fee - $logistic_fee) * $percent_one;

        //上上级用户佣金
        $total_fee_top = ($total_fee - $logistic_fee) * $percent_two;

        //给上级发送佣金
        $this->topOne($total_fee_superior, $total_fee, $sid);

        //记录入库
        $this->record($sid, $uid, $mid, 1, "一级分销", $out_trade_no, $total_fee_superior, time(), 1);

        // 给上级发送模板消息 先查找上级，拿到openid ，然后发送消息
        //$redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();
        $super_user = $this->userOne($sid);
        $tip = "您的积分已发放,请到商城查看";
        $WeChat = new \teach\components\WeChat();
//        while (true) {
//            $formid = $redis->rpop("formid_{$super_user['openid']}");
//            $status = $WeChat->sendMsg($SendWeChatMessage->getScore($super_user['openid'], $formid, $total_fee_superior,$tip));
//            if ($status['errcode'] == 0 || $formid == false) {
//                break;
//            }
//        }
        $WeChat->send($SendWeChatMessage->getScores($super_user["openid"], $total_fee, "分享成功", $tip));


        //给上上级发送佣金
        $this->topTwo($total_fee_top, $total_fee, $tid);

        //记录入库
        $this->record($tid, $uid,$mid, 2, "二级分销", $out_trade_no, $total_fee_top, time(), 1);

        // 给上上级发送模板消息
        $top_user = $this->userOne($tid);
//        $WeChat = new \teach\components\WeChat();
//        while (true) {
//            $formid_top = $redis->rpop("formid_{$top_user['openid']}");
//            $status_top = $WeChat->sendMsg($SendWeChatMessage->getScore($top_user['openid'], $formid_top, $total_fee_top,$tip));
//            if ($status_top['errcode'] == 0 || $formid_top == false) {
//                break;
//            }
//        }
        $WeChat->send($SendWeChatMessage->getScores($top_user["openid"], $total_fee_top, "分享成功", $tip));

        //将pay表改为已支付
        $this->dealPay($p_id);


    }

    /**
     * 给上上级发佣金
     * @param $total_fee_top
     * @param $total_fee
     * @param $tid
     * @return int
     */
    private function topTwo($total_fee_top, $total_fee, $tid)
    {
        $sql = "UPDATE edu_user SET mall_total_fee = mall_total_fee + {$total_fee_top}, mall_use = mall_use + {$total_fee},  mall_order_count = mall_order_count + 1 WHERE id = {$tid}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 同时存在两级时，给上级发佣金
     * @param $total_fee_superior
     * @param $total_fee
     * @param $sid
     * @return int
     */
    private function topOne($total_fee_superior, $total_fee, $sid)
    {
        $sql = "UPDATE edu_user SET mall_total_fee = mall_total_fee + {$total_fee_superior}, mall_use = mall_use + {$total_fee},  mall_order_count = mall_order_count + 1 WHERE id = {$sid}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    //只有一个上级时，给上级打入佣金
    private function superior($uid, $mall_superior_id, $mid, $out_trade_no, $logistic_fee, $total_fee, $p_id, $percent)
    {
        //上级用户得到的佣金
        $total_fee_superior = ($total_fee - $logistic_fee) * $percent;
        $this->superAmount($total_fee_superior, $total_fee, $mall_superior_id);

        //将pay表改为已支付
        $this->dealPay($p_id);

        //将打入的金额记录入表
        $this->record($mall_superior_id, $uid, $mid, 1, "一级分销", $out_trade_no, $total_fee_superior, time(), 1);

        // 发送模板消息
        //$redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();
        $super_user = $this->userOne($mall_superior_id);
        $tip = "您的积分已发放,请到商城查看";
        $WeChat = new \teach\components\WeChat();
//        while (true) {
//            $formid = $redis->rpop("formid_{$super_user['openid']}");
//            $status = $WeChat->sendMsg($SendWeChatMessage->getScore($super_user['openid'], $formid, $total_fee_superior,$tip));
//            if ($status['errcode'] == 0 || $formid == false) {
//                break;
//            }
//        }
        $WeChat->send($SendWeChatMessage->getScores($super_user["openid"], $total_fee_superior, "分享成功", $tip));

        return true;
    }

    /**
     *  记录分配
     * @param $uid
     * @param $sid
     * @param $mid
     * @param $direct
     * @param $direct_text
     * @param $out_trade_no
     * @param $amount
     * @param $create_time
     * @param $status
     * @return int
     */
    private function record($uid, $sid, $mid, $direct, $direct_text, $out_trade_no, $amount, $create_time, $status)
    {
        $map = [
            'uid' => $uid,
            'sid' => $sid,
            'mid' => $mid,
            'direct' => $direct,
            'direct_text' => $direct_text,
            'out_trade_no' => $out_trade_no,
            'amount' => $amount,
            'create_time' => $create_time,
            'status' => $status,
        ];
        return Yii::$app->db->createCommand()->insert('mall_bill', $map)->execute();
    }

    /**
     * 只有一个上级时，给用户分配佣金
     * @param $total_fee_superior
     * @param $total_fee
     * @param $mall_superior_id
     * @return int
     */
    private function superAmount($total_fee_superior, $total_fee, $mall_superior_id)
    {
        $sql = "UPDATE edu_user SET mall_total_fee = mall_total_fee + {$total_fee_superior}, mall_use = mall_use + {$total_fee},  mall_order_count = mall_order_count + 1 WHERE id = {$mall_superior_id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 将mall_pay 改为已经处理
     * @param $p_id
     * @return int
     */
    private function dealPay($p_id)
    {
        $sql = "UPDATE mall_pay SET status = 2 WHERE id = {$p_id}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 获取下单用户
     * @param $uid
     * @return array|false
     */
    private function userOne($uid)
    {
        $sql = "SELECT mall_superior, openid, mall_top, mall_id FROM edu_user WHERE id = {$uid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 查找佣金
     * @param $mid
     * @return array|false
     */
    private function distribution($mid)
    {
        $sql = "SELECT level_one, level_two FROM mall_distribution WHERE state = 1 AND mid = {$mid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }


    /**
     * 查找一条订单
     * @param $oid
     * @param $mid
     * @param $uid
     * @return array|false
     */
    private function sureOrder($oid, $mid, $uid)
    {
        $sql = "SELECT p.id AS p_id, p.out_trade_no, p.total_fee, p.status AS p_status, o.id AS o_id, o.mid, o.uid, o.openid, o.out_trade_no, o.total_fee, o.logistic_fee, o.status AS o_status FROM mall_pay AS p LEFT JOIN mall_order AS o ON p.out_trade_no = o.out_trade_no WHERE p.status = 1 AND o.status = 3 AND o.id = {$oid} AND o.mid = {$mid} AND o.uid = {$uid}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }
}